/**
 * All Rights Reserved , Copyright (C) 2023 , 青岛鼎信通讯股份有限公司
 * <p>
 * QemProblemAlertService
 * 问题告警表
 * <p>
 * 修改纪录
 * 2023-01-06 版本：1.0 xinfushuo 创建。
 *
 * @version 版本：1.0
 * @author 作者：xinfushuo
 * 创建日期：2023-01-06
 */
package com.topscomm.qem.service.impl;

import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.cbo.pojo.CboDeptEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.impl.CboDeptService;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.qem.QemSystemConst;
import com.topscomm.qem.pojo.QemProblemAlertEntity;
import com.topscomm.qem.service.IQemProblemAlertService;
import com.topscomm.qem.service.impl.auto.QemProblemAlertServiceAuto;
import com.topscomm.tap.common.DatacodeCache;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service(value = "qemProblemAlertService")
@Scope(value = "singleton")
public class QemProblemAlertService extends QemProblemAlertServiceAuto implements IQemProblemAlertService {

    private  static  DateTimeFormatter formatter
				= DateTimeFormatter.ofPattern("yyyyMMdd");
    @Autowired
    QemDutyDeptService qemDutyDeptService;
    @Autowired
    private CboUserService cboUserService;
    @Autowired
    private CboDeptService cboDeptService;
    /**
     * @param entity
     * @throws ServiceException
     * @author: xinfushuo
     * @date: 2023-01-06
     * @description:单号生成
     * @modify:
     */
    @Override
    protected void beforeInsert(BasicEntity entity) {
        super.beforeInsert(entity);
        if (entity.getId() <= 0) {// 赋值Id和单号
            long[] arrayId = PrimaryKeyUtil.GeneIDs(entity.getTableName(), 1);
            entity.setId(arrayId[0]);
            String docNo = generateDocno(arrayId[0]);
            entity.setValue(QemProblemAlertEntity.FieldDocno, docNo);
        }
    }

    /**
     * @param id 存储过程生成的id
     * @return 业务规则定义的docno 每天新增超过999即重复
     * PA（problem alarm）+四位数字（年份）+两位数字（月份）+两位数字（日期）+三位数字（流水号）
     * @author xinfushuo
     * @date 2023/1/9
     * @modify
     */
    private String generateDocno(long id) {
        LocalDateTime now = LocalDateTime.now();
        String docno = String.valueOf(id);
        docno = "PA" + now.format(formatter) + docno.substring(docno.length() - 3);
        return docno;
    }
    @Override
    public void setDispFields(Map<String, Object> mapRow, DatacodeCache datacodeCache) {
        super.setDispFields(mapRow, datacodeCache);
        String temp;
        //风险排查负责人
        setDispField(mapRow, QemProblemAlertEntity.FieldRiskman, name -> name + "[" + mapRow.get(QemProblemAlertEntity.FieldRiskmancode) + "]");
        //问题负责分析人
        setDispField(mapRow, QemProblemAlertEntity.FieldAssayer, name -> name + "[" + mapRow.get(QemProblemAlertEntity.FieldAssayercode) + "]");
        //创建人
        setDispField(mapRow, QemProblemAlertEntity.FieldUsername, name -> name + "[" + mapRow.get(QemProblemAlertEntity.FieldUsercode) + "]");
        //问题反馈人
        setDispField(mapRow, QemProblemAlertEntity.FieldFeedbackperson, name -> name + "[" + mapRow.get(QemProblemAlertEntity.FieldFeedbackpersoncode) + "]");
        // 是否违反质量政策
        if (mapRow.get("whetherqualitypolicy") != null) {
            temp = mapRow.get("whetherqualitypolicy").toString();
            mapRow.put("dispwhetherqualitypolicy", datacodeCache.getValueDynamic("CboYesNo", temp, "code", "name"));
        }
    }


    /**
     * @Description:    处理作废业务
     * @Author:         wuyuyang
     * @Return:
     * @exception:
     * @Date:           13/1/2023 下午7:49
     * @Version:        1.0
     **/
    @Transactional
    public Boolean executeCancel(String id, String cancelReason) {
        StringBufferProxy sql = new StringBufferProxy();
        // 1、取有效数据
        sql.appendSingle("id = {0} and enabled = 1", id);
        QemProblemAlertEntity qemProblemAlertEntity = this.queryObjectByWhere(sql.toString());
        // 2、获取当前用户、工号、时间,处理作废原因
        String username = this.getSessionUserBean().getUser().getName();
        String usercode = this.getSessionUserBean().getUser().getCode();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String transformDate = simpleDateFormat.format(new Date());
        String finalCancelReason = "该问题已于" + transformDate + "由 " + username + "(" + usercode + ")" +" 作废!" + "  作废原因: " + cancelReason;
        if(qemProblemAlertEntity != null) {
            // 3、如果当前单据已经审批完成、修改审批状态、作废、赋作废原因
            if(qemProblemAlertEntity.getState() == QemSystemConst.QemProblemAlert_Approved) {
                qemProblemAlertEntity.setEnabled(QemSystemConst.QemProblemAlertEntityEnabled.No);
                qemProblemAlertEntity.setCancelreason(finalCancelReason);
                this.updateEntity(qemProblemAlertEntity);
                return true;
                // 4、如果当前单据状态处于审核中、取消审批状态、修改当前单据状态为审核中、作废、赋作废原因
            } else if(qemProblemAlertEntity.getState() == QemSystemConst.QemProblemAlert_Approveing){
                this.executeDelApprove(id, this.getSessionUserBean());
                qemProblemAlertEntity.setState(QemSystemConst.QemProblemAlert_Approveing);
                qemProblemAlertEntity.setEnabled(QemSystemConst.QemProblemAlertEntityEnabled.No);
                qemProblemAlertEntity.setCancelreason(finalCancelReason);
                this.updateEntity(qemProblemAlertEntity);
                return true;
            }
        }
        return false;
    }

    /**
     * @Description:    查询其他与问题告警单有关单据状态
     * @Author:         wuyuyang
     * @Return:         java.lang.String
     * @exception:
     * @Date:           11/1/2023 下午10:04
     * @Version:        1.0
     **/
    public void queryElseBillState (String id) {
    }

    /**
     * @author: caozhiyuan
     * @date: 2023-01-11 10:49:36
     * @param:
     * @description: 拼接数据权限
     * @return: java.lang.String
     * @modify:
     */
    @Override
    public String spellDataDutyDeptPermission() {
        // 获得获取当前用户拥有权限的责任主体部门，以英文逗号分割
        List<String> dutyDeptCodes = qemDutyDeptService.getAuthorizationByActiveUser();
        // 处理数据
        String sqlDutyDeptCodes = dutyDeptCodes.stream().map(item -> "'" + item + "'").collect(Collectors.joining(","));
        StringBufferProxy sql = new StringBufferProxy();
        // 无权限，不显示任何数据
        if (StringUtil.isEmpty(sqlDutyDeptCodes)) {
            sql.appendSingle("and 1<>1");
        } else {
            // 判断问题归属产品线或牵头分析部门是否属于权限中的code
            sql.appendSingle("and ((" + QemProblemAlertEntity.FieldProductline + " in (" + sqlDutyDeptCodes +")) or (" +
                    QemProblemAlertEntity.FieldDutydept + " in (" + sqlDutyDeptCodes + ")))");
        }
        return sql.toString();
    }


    /**
     * @Description:    查询当前用户的直级领导，如果没找到不做任何处理
     * @Author:         wuyuyang
     * @Return:         java.lang.String
     * @exception:
     * @Date:           2/2/2023 下午3:43
     * @Version:        1.0
     **/
    @Transactional
    public HashMap<String, Object> queryDirectLeaderCode() {
        String userCode = this.getSessionUserBean().getUser().getCode();
        try{
            // 查询到当前用户的具体部门
            StringBufferProxy sql = new StringBufferProxy();
            HashMap<String, Object> map = new HashMap<String, Object>();
            sql.appendSingle("id = (select deptid from cbouser where code = '{0}')", userCode);
            CboDeptEntity cboDeptEntity = cboDeptService.queryObjectByWhere(sql.toString());
            CboUserEntity cboUserEntity = cboUserService.queryById(cboDeptEntity.getHeaderids());
            // 当查询用户发现是自己时，就往上级部门查询上级部门领导
            if(cboUserEntity.getCode().equals(userCode)){
                String deptcode = cboDeptEntity.getCode();
                deptcode = deptcode.substring(0, deptcode.length()-2);
                CboDeptEntity cboDeptEntity1 = cboDeptService.queryObjectByWhere("code = '" + deptcode + "'");
                CboUserEntity cboUserEntity1 = cboUserService.queryById(cboDeptEntity1.getHeaderids());
                // 将结果集合成map返回
                map.put("leadercode", cboUserEntity1.getCode());
                map.put("leadername", cboUserEntity1.getName());
                if(!StringUtils.isEmpty(cboUserEntity1.getCode()) && !StringUtils.isEmpty(cboUserEntity1.getName())){
                    return map;
                }else{
                    //不做任何处理
                }
            } else{
                // 将结果集合成map返回
                map.put("leadercode", cboUserEntity.getCode());
                map.put("leadername", cboUserEntity.getName());
                if(!StringUtils.isEmpty(cboUserEntity.getCode()) && !StringUtils.isEmpty(cboUserEntity.getName())){
                    return map;
                }else{
                    //不做任何处理
                }
            }
        }catch(Exception e){
            //不做任何处理
        }
        return null;
    }
}
